<template>
  <div class="box">
    <van-nav-bar title="家庭" left-arrow @click-left="onClickLeft" />
    <van-form>
      <van-field v-model="familyList.name" name="name" label="姓名" placeholder="请输入收货人姓名" />
      <van-field v-model="familyList.phone" name="phone" label="+86" placeholder="请输入家庭救诊人手机号" />
      <van-field v-model="familyList.address" is-link readonly name="address" label="所在地区" placeholder="点击选择省市区"
        @click="showArea = true" />
        <van-field v-model="familyList.idCard"  name="idCard" label="身份证" placeholder="请输入身份证号"/>
        <van-field v-model="familyList.age" name="age" label="年龄" placeholder="请输入收货人姓名" />
        
      <van-popup v-model:show="showArea" position="bottom">
        <van-area :area-list="areaList" @confirm="onConfirm" @cancel="showArea = false" />
      </van-popup>
      <div class="box1">
      </div>
      <div class="box2">
        <van-button v-if="!route.query.item" round block type="primary" @click="onSubmit">
          保存
        </van-button>
        <van-button v-else round block type="primary" @click="EditSubmit">
          编辑
        </van-button>
      </div>
    </van-form>

  </div>
</template>

<script lang="ts" setup>
import { reactive, ref,watch } from 'vue';
import axios from 'axios'
import { showNotify } from 'vant';
import { areaList } from '@vant/area-data';
import { useRouter, useRoute } from 'vue-router';
import {  onMounted, defineProps } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
const onClickLeft = () => history.back();

const router = useRouter();
const route = useRoute()
const showArea = ref(false);

const props = defineProps({
  message: String
})

const keyword = ref('')
const longitude = ref(null)
const latitude = ref(null)
const places = ref([]) // 存储搜索结果
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:address', 'childEvent'])
let map
let marker // 定义标记变量

const initMap = () => {
  AMapLoader.load({
    key: 'be64c3933f21b1cf456735c678152f48',
    version: '1.4.15',
    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
  }).then((AMap) => {
    map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 10,
      center: [116.397428, 39.90923]
    })
    emit('childEvent', 'Hello from Child!')

    map.on('click', async (e) => {
      longitude.value = e.lnglat.lng
      latitude.value = e.lnglat.lat
      emit('longitudeLi', longitude.value)
      emit('latitudeLi', latitude.value)

      const apiKey = 'be64c3933f21b1cf456735c678152f48'
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude.value},${latitude.value}`
      try {
        const response = await fetch(url)
        const data = await response.json()

        if (data.status === '1') {
          const address = data.regeocode.formatted_address
          emit('addressLi', address)
        }
      } catch (error) {
        console.error('请求错误:', error)
      }
    })
  }).catch((error) => {
    console.error('加载 AMap 失败:', error)
  })
}

// 搜索地点
const searchPlace = async () => {
  const apiKey = 'be64c3933f21b1cf456735c678152f48'
  const url = `https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(keyword.value)}&key=${apiKey}&extensions=all`
  
  try {
    const response = await fetch(url)
    const data = await response.json()
    if (data.status === '1') {
      places.value = data.pois // 存储搜索结果
    } else {
      console.error('搜索失败:', data.info)
      places.value = []
    }
  } catch (error) {
    console.error('请求错误:', error)
  }
}

// 选择搜索的地点
const selectPlace = (place:any) => {
  longitude.value = place.location.split(',')[0]
  latitude.value = place.location.split(',')[1]
  emit('longitudeLi', longitude.value)
  emit('latitudeLi', latitude.value)
  
  // 在地图上添加标记
  if (marker) {
    marker.setMap(null) // 如果已存在标记，则移除
  }
  
  marker = new AMap.Marker({
    position: [longitude.value, latitude.value], // 设置标记的位置
    title: place.name // 设置标记的标题
  });
  
  marker.setMap(map); // 将标记添加到地图上

  console.log(`选择地点: ${place.name}, 经度: ${longitude.value}, 纬度: ${latitude.value}`)
}
watch(keyword, (newVal) => {
  if (!newVal) {
    places.value = []; // 清空搜索结果
  }
});
// 在组件挂载后初始化地图
onMounted(initMap)

const onConfirm = ({ selectedOptions }) => {
  showArea.value = false;
  familyList.address = selectedOptions.map((item: any) => item.text).join(' ');
};
// 参数·              
const familyList = reactive({
  id: '',
  name: '',
  phone: '',
  address: '',
  age:'',
  idCard:''
} as any)


// 确定编辑
const Edit = async () => {
  const item = JSON.parse(route.query.item as any)

  if (item) {
    console.log('编辑')
    console.log(item)
    familyList.id = item.id
    familyList.name = item.name
    familyList.phone = item.phone
    familyList.address = item.address
    familyList.age = item.age
    familyList.idCard = item.idCard
  } else {
    console.log('添加')
  }
}
Edit()


// 添加提交
const onSubmit = async () => {
  // 验证
  if (familyList.name == '' || familyList.phone == '' || familyList.address == ''|| familyList.age == ''||familyList.idCard == '') {
    showNotify({ type: 'warning', message: '请填写完整信息' });
    return;
  }
  // 也可以在此提交到后台
  const res = await axios.post('/api/v1/addconsultation', {
    name: familyList.name,
    phone: familyList.phone,
    address: familyList.address,
    age: familyList.age,
    idCard: familyList.idCard
  })
  console.log(res)
  if (res.data.code == 200) {
    showNotify({ type: 'success', message: '添加成功' });
    router.push('/jiating')
    console.log(res);
  } else {
    alert('提交失败')
  }

};

// 编辑后提交
const EditSubmit = async () => {
  const res = await axios.put('/api/v1/EditCon', {
    id: familyList.id,
    name: familyList.name,
    phone: familyList.phone,
    address: familyList.address,
    age: familyList.age,
    idCard: familyList.idCard
  })
  console.log(familyList.id)
  console.log(res)
    showNotify({ type: 'success', message: '编辑成功' });
    router.push('/jiating')
  
};


// 根据地图搜索框内容地图跳转到对应地点


</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100vh;

  .box1 {
    width: 100%;
    height: 100px;
    overflow: hidden;
    // border-top: 1px solid #ccc;dw
    // border-bottom: 1px solid #ccc;

    dl {
      display: flex;
      align-items: center;
      width: 100%;
      height: 100px;

      dt {
        font-size: 15px;
        margin-left: 20px;
      }

      dd {
        margin-left: 30px;

        textarea {
          font-size: 14px;
          padding: 10px;
          border: none;
        }
      }
    }
  }

  .box2 {
    margin: 16px;
    position: fixed;
    bottom: 50px;
    left: 0;
    width: 90%
  }

}
 #container {
    padding: 0;
    margin: 0;
     width: 100%;
    height: 376px;
  }
  
  #keyword {
    margin-top: 1%;
    height: 30px;
    position: absolute;
    z-index: 999999;
  }
  
  /* 自定义按钮样式 */
  button {
    margin-top: 10px;
    padding: 5px 10px;
  }

  .results { 
  position: absolute;
  top: 30px; /* 根据需要调整 */
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在地图之上 */
  background-color: white; /* 设定背景颜色 */
  border: 1px solid #ccc; /* 可选的边框 */
  width: 150px; 
  overflow-y: scroll;
}
</style>  